<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card>
      <!-- 搜索与添加功能 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUesrLiset"
          >
            <el-button @click="findUser(queryInfo.query)" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- 用作用域插槽的访问并渲染出数据 -->
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              @change="userStateChaged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <!-- 用作用域插槽的访问并修改出数据 -->
          <template v-slot="scope">
            <!-- 修改 -->
            <el-button
              icon="el-icon-edit"
              type="primary"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              icon="el-icon-delete"
              type="danger"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                icon="el-icon-setting"
                type="warning"
                @click="setRole(scope.row)"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户的对话话框 -->
    <el-dialog title="添加用户" @close="addDialogClosed" :visible.sync="addDialogVisible" width="50%">
      <!-- 内容主题 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="addForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
          <el-input v-model="addForm.passWord"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="EditDialogVisible" width="50%">
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%"
    @close="setRoleDialogClosed">
      <div>
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择角色">
            <el-option
              v-for="(item,index) in roleList"
              :key="index"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      //邮箱正则
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号规则
    var checkMobile = (rule, value, cb) => {
      //手机号正则
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) return cb()
      cb(new Error('请输入合法的手机号'))
    }
    return {
      //获取用户列表的参数对象
      queryInfo: {
        //   搜索关键字
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2,
      },
      userlist: [],
      total: 0,
      // 角色分配对话框 dialog显示与隐藏
      setRoleDialogVisible: false,
      // 添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 修改用户对话框的显示与隐藏
      EditDialogVisible: false,

      // 添加用户的验证对象
      addForm: {
        userName: '',
        passWord: '',
        email: '',
        mobile: '',
      },
      // 添加用户验证规则对象
      addFormRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        passWord: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 15 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      // 表单对象
      editForm: {},
      // 表单验证规则对象
      editFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色数据列表
      roleList: [],
      // 已经选中的角色id值
      selectedRoleId:[]
    }
  },
  created() {
    this.handleSizeChange()
    this.handleCurrentChange()
  },
  methods: {
    async getUesrLiset() {
      const { data: res } = await this.$http.get('user', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) return this.$message.error('获取用户失败')
      this.userlist = res.data.users
      this.total = res.data.totalpage
      return res
    },
    // 监听pagesize 事件
    handleSizeChange(newsize = 2) {
      // newsize 是当前这一页显示多少条
      // 先获取全部的数据然后进行裁剪
      const _that = this
      this.getUesrLiset().then((res) => {
        _that.queryInfo.pagesize = newsize
        const sum = _that.queryInfo.pagesize * _that.queryInfo.pagenum
        if (sum >= _that.total) {
          if (_that.queryInfo.pagenum === 1)
            _that.userlist = _that.userlist.slice(0)
          else
            _that.userlist = _that.userlist.slice(
              _that.queryInfo.pagesize * (_that.queryInfo.pagenum - 1)
            )
        } else {
          if (_that.queryInfo.pagenum === 1)
            _that.userlist = _that.userlist.slice(0, _that.queryInfo.pagesize)
          else
            _that.userlist = _that.userlist.slice(
              _that.queryInfo.pagesize * (_that.queryInfo.pagenum - 1),
              _that.queryInfo.pagesize * _that.queryInfo.pagenum
            )
        }
      })
    },
    // 监听页面值 改变的事件
    handleCurrentChange(newpage = 1) {
      const _that = this
      this.getUesrLiset().then(() => {
        _that.queryInfo.pagenum = newpage
        //  _that.queryInfo.pagesize 这是 当前页应该显示的 条数
        //   获取 该页及之前 所有的 总数
        const sum = _that.queryInfo.pagesize * _that.queryInfo.pagenum
        // 1.假如 sum > this.total  4 *2  >= 8 那么  上一页是 8-4*1
        if (sum >= _that.total) {
          // 应该是
          if (_that.queryInfo.pagenum !== 1)
            _that.userlist = _that.userlist.slice(
              (_that.queryInfo.pagenum - 1) * _that.queryInfo.pagesize
            )
          else  _that.userlist = _that.userlist.slice( 0,
              sum -  _that.total
            )
        }
        // 2.假如 sum < this.total 3*2 < 7    那么这一页应该显示 3-6 这3 条 上一页也是显示了3条 _that.queryInfo.pagesize *
        else {
          if (_that.queryInfo.pagenum === 1)
            _that.userlist = _that.userlist.slice(
              0,
              _that.queryInfo.pagenum * _that.queryInfo.pagesize
            )
          else
            _that.userlist = _that.userlist.slice(
              (_that.queryInfo.pagenum - 1) * _that.queryInfo.pagesize,
              _that.queryInfo.pagenum * _that.queryInfo.pagesize
            )
        }
      })
    },
    // 监听switch 开关状态的改变
    async userStateChaged(userInfo) {
      console.log(userInfo)
      // 这里只需要向后端发送数据即可。
      const { data: res } = await this.$http.put(`user/state`, {
        id: userInfo.id,
        state: userInfo.mg_state,
      })

      if (res.meta.status !== 200) {
        // 如果失败 还是原来的状态
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新状态成功')
    },
    // 搜索用户
    findUser(userName) {
      if (!userName) this.getUesrLiset()
      this.userlist = this.userlist.filter((item) => {
        return item.username.indexOf(userName) !== -1
      })
    },
    // 点击取消按钮，重置表单 (添加用户对话框)
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定按钮，添加新用户(添加用户对话框)
    addUser() {
      // 拿到表单的实例对象 ： this.$refs.addFormRef
      this.$refs.addFormRef.validate(async (valid) => {
        console.log(valid)
        if (!valid) return;
        // 如果校验成功则发起添加用户请求
        const { data: res } = await this.$http.post('user', this.addForm)
        if (res.meta.status !== 201) this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        //隐藏添加用户的列表
        this.addDialogVisible = false
        //  这里需要往数据库添加数据
        var now = new Date().getDate()
        console.log(this.userlist, this.addForm)
      })
    },
    // 编辑用户的对话框
    showEditDialog(id) {
      this.EditDialogVisible = true
      // 通过scope.row 作用域插槽，拿到用户信息
      // 结构复制拿到id
      const [editUserInfo] = this.userlist.filter((item) => {
        return item.id === id
      })
      this.editForm = editUserInfo
    },
    // 修改用户对话框的关闭事件
    // editDialogClosed(){
    //   this.$refs.editFormRef.resetFields()
    // },
    // 修改用户信息并提交
    editUserInfo() {
      let _that = this
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        //  校验通过发送请求
        const { data: res } = await _that.$http.put(`/user`, {
          email: _that.editForm.email,
          mobile: _that.editForm.mobile,
        })
        if (res.meta.status !== 200) return _that.$message.error('更新用户失败')
        // 如果成功
        console.log(_that.userlist, _that.editForm)
        // 1.关闭对话框
        _that.EditDialogVisible = false
        // 2.刷新数据列表
        _that.userlist.splice(
          _that.userlist.findIndex((item) => item.id === this.editForm.id),
          1,
          _that.editForm
        )
        // console.log(_that.userlist)
        // 3.提示修改成功
        _that.$message.success('修改成功')
      })
    },
    // 根据id删除用户的信息
    async removeUserById(id) {
      // 询问用户是否删除用户信息
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 如果用户点击了确认删除，则返回字符串'confirm'
      // 如果用户点击了取消删除，本应该会报错。但是我们进行了catch(err=>{return err}); 此时返回的'cancel'
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete('user', { id })
      if (res.meta.status !== 200) {
        return this.message.error('请求失败')
      }
      // 刷新数据
      this.userlist.splice(
        this.userlist.findIndex((item) => item.id === id),
        1
      )
      //
    },
    // 展示分配角色对话框
    async setRole(userInfo) {
      this.userInfo = userInfo
      //展示对话框之前获取所有角色列表
      const { data: res } = await this.$http.get('/role')
      if (res.meta.status !== 200) {
        return this.$message.error('请求失败')
      }
      this.roleList = res.data
      this.setRoleDialogVisible = true
    },
    async saveRoleInfo(){
      if(!this.selectedRoleId){
        return this.$message.error('请选中要分配的角色')
      }

      // 如果选择了分配角色那么进行数据请求
      const {data:res} = await this.$http.get('/rights/tree')
      if(res.meta.status !== 200) return this.$message.error('请求失败')
      this.userInfo.role_name = res.data.filter(item => item.id === this.selectedRoleId)[0].roleName;
      this.setRoleDialogVisible = false

    },
    setRoleDialogClosed(){
      this.userInfo = {};
      this.selectedRoleId = '';
    }
  },
}
</script>
<style lang="less" scoped>
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 15px;
}
</style>

